package com.atguigu.gmall.realtime.app;

import com.atguigu.gmall.realtime.util.MyKafkaUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.filesystem.FsStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/15 9:33
 */
public abstract class BaseAppV2 {
    
    public abstract void run(StreamExecutionEnvironment env,
                             Map<String, DataStreamSource<String>> sourceStreams);
    
    public void init(int port, int parallelism, String ck, String groupId, String ... topics) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(parallelism);
        env.enableCheckpointing(5000, CheckpointingMode.EXACTLY_ONCE);
        env.setStateBackend(new FsStateBackend("hdfs://hadoop162:8020/gmall0922/" + ck));
        env.getCheckpointConfig().setCheckpointTimeout(60000);
        env
            .getCheckpointConfig()
            .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
    
        // dwd_order_info, dwd_order_detail
        final Map<String, DataStreamSource<String>> sourceStreams = new HashMap<>();
        for (String topic : topics) {
            final DataStreamSource<String> stream = env.addSource(MyKafkaUtil.getFlinkKafkaSource(groupId, topic));
            sourceStreams.put(topic, stream);
        }
        
        // 插入不同的代码
        run(env, sourceStreams);
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
